package com.java.base.exercise.current;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author RenPu
 * @Date 2022/1/3 10:21
 * @Version 1.0
 * @Description:
 **/
public class AtomicUnsafe {

    // volatile 保证指令重排序，以及线程的可见性
  private   volatile int i=0;

    //使用Unsafe的类实现CAS的实现
    static Unsafe unsafe=null;
    //第一种使用同步锁优化
//    public synchronized void add(){
//        i++;
//    }
    static long offserSet;

    static {
        try {

            //利用反射拿到Unsafe对象
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe=(Unsafe)theUnsafe.get(null);
            //Unsafe利用属性偏移量，定位到属性位于对象内具体的内存地址
             offserSet = unsafe.objectFieldOffset(AtomicUnsafe.class.getDeclaredField("i"));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //使用Unsafe类，完成CAS的编写
    public  void add(){
        //当前值
        int current;
        //累加后的新值
        int newI;
        do{
            //i++
            //根据偏移量，获取对象属性内存地址，所对应的值
            current=unsafe.getIntVolatile(this,offserSet);
            newI=current+1;
            //所需要的参数，参与计算属性所属的对象，属性位于对象内的偏移量，当前值，期望值
            //如果不成功则进行重试
        }while (!unsafe.compareAndSwapInt(this,offserSet,current,newI));

    }


    public static void main(String[] args) {

//        AtomicInteger atomicInteger = new AtomicInteger();

        AtomicUnsafe atomicUnsafe = new AtomicUnsafe();
        for (int i = 0; i <2 ; i++) {
            new Thread(()->{
                for (int j = 0; j <10000 ; j++) {
                    atomicUnsafe.add();

                }

            }).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println(
                    atomicUnsafe.i
            );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}
